import common from '@/mixins/common.js';
import Protocol from '../wechatApplymentnew/wechatLittleCustomApplymentnew/component/protocol';
export default {
	name: 'savePayMerchantInfo',

	mixins: [common],

	components: {
		Protocol
	},

	data() {
		let checkMobile = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('不能为空'));
			} else {
				let reg = /^1\d{10}$/;
				if (reg.test(value)) {
					callback();
				} else {
					callback(new Error('手机号码不合法'));
				}
			}
		};
		let checkEmail = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('不能为空'));
			} else {
				let reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
				if (reg.test(value)) {
					callback();
				} else {
					callback(new Error('邮箱格式不合法'));
				}
			}
		};
		let checkIdCard = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('不能为空'));
			} else {
				let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
				if (reg.test(value)) {
					callback();
				} else {
					callback(new Error('证件号码不合法'));
				}
			}
		};
		return {
			// isAgreen: false,//车场协议是否同意
			currentTab: '主要信息', //主要信息，车场协议
			isReadTip: true,
			firstInThisPage:true,
			businessLicenList: [],
			idCardFrontList: [],
			idCardBackList: [],
			PIDtipVisible: false,
			merchantInfo: {
				name: '',
				phone: '',
				email: '',
				mchId: '',
				businessName: '',
				merchantMail: '',
				businessLicenseCode: '',
				id: null,
				createBy: sessionStorage.getItem('loginid'),
				operatorId: sessionStorage.getItem('_operatorID'),
				payPlatform: this.$route.query.payPlatform,
				parkId: this.$route.query.parkId
			},
			rules: {
				name: [],
				phone: [{ validator: checkMobile, trigger: 'blur' }],
				email: [{ validator: checkEmail, trigger: 'blur' }],
				businessName: [],
				merchantMail: [{ trigger: 'blur' }],
				businessLicenseCode: []
			}
		};
	},

	created() {
		let _requiredRule = { required: true, message: '不能为空', trigger: ['change', 'blur'] };
		let _rules = this.rules;
		for (let name in _rules) {
			_rules[name].push(_requiredRule);
		}
		let _query = this.$route.query;
		this.query = _query;

		if (_query.merchantId !== undefined) {//存在则是修改账号资料
			this.getParkPayMerchantInfo();
		}else if(_query.merchantId === undefined){//不存在则是新增
			this.getWeixinUser(this.query.parkId);
		}
	},

	mounted() {
		this.$nextTick(() => {
			let scrollEl = document.getElementsByClassName('el-scrollbar__wrap')[0]
			scrollEl.scrollTop = 0
		})
	},

	methods: {
		// 获取账号信息
		getParkPayMerchantInfo() {
			let self = this;
			let params = {
				merchantId: this.query.merchantId
			};
			API.fetchGet('/valueAdded/getParkPayMerchantInfo', params).then(
				data => {
					self.merchantInfo = data;
					self.merchantInfo.parkId = this.query.parkId;
					self.merchantInfo.payPlatform = this.query.payPlatform;
					if (data.businessLicense) {
						self.businessLicenList.push({ url: data.businessLicense });
					}
					if (data.idCardFront) {
						self.idCardFrontList.push({ url: data.idCardFront });
					}
					if (data.idCardBack) {
						self.idCardBackList.push({ url: data.idCardBack });
					}
				},
				err => [
					self.showToast('账号资料获取失败！', 2, 1500)
				]
			);
		},

		//查看车场协议
		toProtocol() {
			this.currentTab = '车场协议';
		},
		goStep(tabName) {
			this.currentTab = tabName;
		},

		//PID弹窗
		handlePIDClose(done) {
			let self = this;
			self.PIDtipVisible = !self.PIDtipVisible;
		},

		//获取url配置
		// getUrlPara(name) {
		//   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
		//   var r = window.location.search.substr(1).match(reg);
		//   if (r!=null) {return (r[2])}else{ return null };
		// },

		//新增商户支付的微信配置（如果有则拿过来）
		getWeixinUser(parkIdcode) {
			let params = {
				parkId: parkIdcode
			};
			API.fetchGet('/valueAdded/getParkWechatMerchantInfoByParkId', params).then(
				res => {
					if (res) {
						this.merchantInfo.name = res.name
						this.merchantInfo.phone = res.phone
						this.merchantInfo.email = res.email
						this.merchantInfo.businessLicenseCode = res.businessLicenseCode
						this.merchantInfo.businessName = res.businessName
					}
				},
				err => {
					console.log(err)
				}
			);
		},
		// 新增商户支付配置
		savePayMerchantInfo() {
			let params = JSON.parse(JSON.stringify(this.merchantInfo));
			this.$refs['addAccountForm'].validate(isValid => {
				if (isValid) {
					API.fetchPost('/valueAdded/savePayMerchantInfo', params).then(
						res => {
							this.showToast('提交资料成功！', 1, 1500);
							setTimeout(() => {
								this.back();
							}, 1500);
						},
						err => {
							let _data = err && err.data ? err.data : {};
							let msg = _data.message || '提交失败';
							this.showToast(msg, 2, 1500);
						}
					);
				}
			});
		},

		changeUploadListVal(file, fileList, name, paramName) {
			if (fileList.length > 0) {
				this[name].push(file);
				this.getBase64Url(file, paramName);
			} else {
				let _idx = paramName.indexOf('Base64');
				let _picName = paramName.substr(0, _idx);
				this[name] = [];
				this.merchantInfo[paramName] = null;
				if (this.merchantInfo[_picName]) {
					this.merchantInfo[_picName] = null;
				}
			}
		},

		getBase64Url(file, paramName) {
			let self = this;
			if (file.raw) {
				let reader = new FileReader();
				reader.readAsDataURL(file.raw);
				reader.onload = function(e) {
					let _res = this.result;
					self.merchantInfo[paramName] = _res.split(';base64,')[1];
				};
			}
		},

		changeIdCardFrontList(file, fileList) {
			this.changeUploadListVal(file, fileList, 'idCardFrontList', 'idCardFrontBase64');
		},
		changeIdCardBackList(file, fileList) {
			this.changeUploadListVal(file, fileList, 'idCardBackList', 'idCardBackBase64');
		},

		changeBusinessLicen(file, fileList) {
			this.changeUploadListVal(file, fileList, 'businessLicenList', 'businessLicenBase64');
		},
		back() {
			this.$router.push({
				name: 'onlinePayment'
			});
		}
	}
};
